
  <div class="layui-card">
    <div class="layui-card-body">
      <div class="layui-form-item" style="margin-bottom: 15px;">
        <div class="layui-inline">
          <input type="text" id="searchInput" placeholder="搜索用户名、IP或URI" class="layui-input" style="width: 250px;">
        </div>
        <div class="layui-inline">
          <button class="layui-btn" onclick="searchLogs()"><i class="layui-icon layui-icon-search"></i> 搜索</button>
          <button class="layui-btn layui-btn-primary" onclick="fetchData()"><i class="layui-icon layui-icon-refresh"></i> 刷新</button>
        </div>
        <div class="layui-inline" style="float: right;">
          <button class="layui-btn layui-btn-danger" onclick="clearOldLogs()"><i class="layui-icon layui-icon-delete"></i> 清空7天前日志</button>
        </div>
      </div>

      <!-- 表格 -->
      <table class="layui-table" lay-skin="line">
        <thead>
          <tr>
            <th width="60">ID</th>
            <th width="100">用户</th>
            <th width="130">IP地址</th>
            <th width="80">请求方法</th>
            <th width="200">访问URI</th>
            <th width="150">URL参数</th>
            <th>请求体</th>
            <th width="150">创建时间</th>
          </tr>
        </thead>
        <tbody id="logsTableBody">
          <tr>
            <td colspan="8" style="text-align: center; padding: 20px;">
              <i class="layui-icon layui-icon-loading layui-icon layui-anim layui-anim-rotate layui-anim-loop"></i>
              加载中...
            </td>
          </tr>
        </tbody>
      </table>

      <!-- 分页 -->
      <div id="pagination" style="text-align: right;"></div>
    </div>
  </div>

<script>
layui.use(['layer', 'laypage'], function(){
  var layer = layui.layer;
  var laypage = layui.laypage;
  
  var logsData = [];
  var filteredData = [];
  var currentPage = 1;
  var pageSize = 20;
  
  // 获取日志数据
  window.fetchData = function() {
    fetch('/logs')
      .then(response => response.json())
      .then(result => {
        if (result.result && result.data) {
          logsData = result.data;
          filteredData = logsData;
          renderTable();
          renderPagination();
        } else {
          layer.msg('数据加载失败', {icon: 2});
        }
      })
      .catch(error => {
        console.error('Error:', error);
        layer.msg('请求失败', {icon: 2});
      });
  }
  
  // 搜索日志
  window.searchLogs = function() {
    var keyword = document.getElementById('searchInput').value.trim().toLowerCase();
    if (!keyword) {
      filteredData = logsData;
    } else {
      filteredData = logsData.filter(function(log) {
        return (log.user && log.user.toLowerCase().indexOf(keyword) >= 0) ||
               (log.ip && log.ip.toLowerCase().indexOf(keyword) >= 0) ||
               (log.uri && log.uri.toLowerCase().indexOf(keyword) >= 0);
      });
    }
    currentPage = 1;
    renderTable();
    renderPagination();
  }
  
  // 渲染表格
  function renderTable() {
    var tbody = document.getElementById('logsTableBody');
    var html = '';
    
    if (filteredData.length === 0) {
      html = '<tr><td colspan="8" style="text-align: center; padding: 20px;">暂无数据</td></tr>';
    } else {
      var start = (currentPage - 1) * pageSize;
      var end = Math.min(start + pageSize, filteredData.length);
      
      for (var i = start; i < end; i++) {
        var log = filteredData[i];
        
        // 根据请求方法设置颜色
        var methodClass = '';
        var methodText = log.method || '-';
        switch(methodText) {
          case 'GET':    methodClass = 'layui-bg-blue'; break;
          case 'POST':   methodClass = 'layui-bg-green'; break;
          case 'PUT':    methodClass = 'layui-bg-orange'; break;
          case 'DELETE': methodClass = 'layui-bg-red'; break;
          case 'PATCH':  methodClass = 'layui-bg-cyan'; break;
          default:       methodClass = 'layui-bg-gray'; break;
        }
        
        html += '<tr>';
        html += '<td>' + log.id + '</td>';
        html += '<td>' + (log.user || '-') + '</td>';
        html += '<td>' + (log.ip || '-') + '</td>';
        html += '<td><span class="layui-badge ' + methodClass + '">' + methodText + '</span></td>';
        html += '<td>' + (log.uri || '-') + '</td>';
        html += '<td><div style="max-width: 150px; overflow: hidden; text-overflow: ellipsis; white-space: nowrap;" title="' + (log.param || '') + '">' + (log.param || '-') + '</div></td>';
        html += '<td><div style="max-width: 300px; overflow: hidden; text-overflow: ellipsis; white-space: nowrap;" title="' + (log.body || '') + '">' + (log.body || '-') + '</div></td>';
        html += '<td>' + (log.createTime || '-') + '</td>';
        html += '</tr>';
      }
    }
    
    tbody.innerHTML = html;
  }
  
  // 渲染分页
  function renderPagination() {
    if (filteredData.length === 0) {
      document.getElementById('pagination').innerHTML = '';
      return;
    }
    
    laypage.render({
      elem: 'pagination',
      count: filteredData.length,
      limit: pageSize,
      curr: currentPage,
      layout: ['count', 'prev', 'page', 'next', 'limit', 'skip'],
      limits: [10, 20, 50, 100],
      jump: function(obj, first) {
        currentPage = obj.curr;
        pageSize = obj.limit;
        if (!first) {
          renderTable();
        }
      }
    });
  }
  
  // 清空7天前的日志
  window.clearOldLogs = function() {
    layer.confirm('确定要清空7天前的操作日志吗？此操作不可恢复！', {
      icon: 3,
      title: '清空日志'
    }, function(index) {
      var loading = layer.load(2);
      
      fetch('/logs', {
        method: 'DELETE'
      })
      .then(response => response.json())
      .then(result => {
        layer.close(loading);
        if (result.result) {
          layer.msg('日志已清空', {icon: 1});
          fetchData();
        } else {
          layer.msg('清空失败: ' + (result.message || '未知错误'), {icon: 2});
        }
        layer.close(index);
      })
      .catch(error => {
        layer.close(loading);
        console.error('Error:', error);
        layer.msg('请求失败', {icon: 2});
      });
    });
  }
  
  // 页面加载时获取数据
  fetchData();
  
  // 搜索框回车事件
  document.getElementById('searchInput').addEventListener('keypress', function(e) {
    if (e.key === 'Enter') {
      searchLogs();
    }
  });
});
</script>
